/**
 * Created by George on 2018/1/27.
 * 用户列表
 */

import util from "../common/util"


// 将本控制器函数作为结果返回给router.js
var userCtrl = function ($scope, $http) {
    $scope.welcome_info = "会员管理";
    $scope.memberListDatas = [];
    $scope.dues = {
        consume: 0,
        realConsume: 0,
        leave: 0
    };
    $scope.pageItems = [5, 10, 20, 30, 50, 100];
    $scope.pageInfo = {
        pageNo: 1,
        pageSize: 100,
        totalCnt: 0,
        pageNum: 1
    };
    $scope.$emit('updateRoute', 'user');

    function initOrUpdateData() {
        $scope.dues = {
            consume: 0,
            realConsume: 0,
            leave: 0
        };

        $http.get("/basketballfire/rest/user/list", {params: $scope.pageInfo}).then(function (data) {
            console.log(data);
            $scope.pageInfo.totalCnt = data.data.totalCnt;
            $scope.pageList = [];
            var pageNum = Math.ceil($scope.pageInfo.totalCnt / $scope.pageInfo.pageSize); //分页数
            for (var index = 0; index < pageNum; index++) {
                $scope.pageList.push(index + 1);
            }
            $scope.pageInfo.pageNum = pageNum;
            var usersData = data.data.data;
            usersData.sort(function(a, b){return a.name.localeCompare(b.name)});
            initUsersData(usersData);
        });
    }

    function init() {
        initOrUpdateData();
    }

    function initUsersData(usersData) {
        $scope.dues.leave = 0;
        var index;
        for (index = 0; index < usersData.length; index++) {
            $scope.dues.leave = util.add($scope.dues.leave, usersData[index].dues);
        }

        $scope.memberListDatas = [];
        for (index = 0; index < usersData.length;) {
            var data = {
                left: {},
                right: {}
            };
            data.left = usersData[index];
            if (index + 1 < usersData.length) {
                data.right = usersData[index + 1];
            }
            $scope.memberListDatas.push(data);
            index += 2;
        }
    }

    $scope.selectPage = function (pageNo, pageSize) {
        $scope.pageInfo.pageNo = pageNo;
        $scope.pageInfo.pageSize = pageSize;
        initOrUpdateData();
    };

    //ctrl start
    init();
};

export default userCtrl;